using MeiWinForms.comm;
using MeiWinForms.communication;
using MeiWinForms.module;
using static MeiWinForms.comm.Config;
using Timer = System.Threading.Timer;

namespace MeiWinForms;

public partial class FormMain : Form
{
    private readonly Client _client = Client.GetClient();

    public FormMain()
    {
        InitializeComponent();
        InitTray();

        Output.Subscribe(WriteOutput);
        Notify.Subscribe("heartbeat", OnHeartbeatNotify);

        RunTask(SqlBackup.Backup);
        RunTask(Heartbeat.Heart);
        RunTask(_client.Listen);
    }
    
    protected override void OnFormClosing(FormClosingEventArgs e)
    {
        _client.Close();
        base.OnFormClosing(e);
        // 一秒后强制关闭，防止client死循环未结束
        var timer = new Timer(_ => Environment.Exit(0));
        timer.Change(1000, Timeout.Infinite);
    }

    private void WriteOutput(string message)
    {
        // WinForm不允许在其他线程操作控件，需要用Invoke转一下
        textBoxOutput.Invoke(() => textBoxOutput.Text += message + Environment.NewLine); // TODO 每次更新内容之后，滚动条会回到最顶端
    }

    private void OnHeartbeatNotify()
    {
        // 将窗体切换到前台
        Invoke(() =>
        {
            WindowState = FormWindowState.Normal; // 如果窗体被最小化，恢复为正常状态
            BringToFront(); // 将窗体带到前台
            Activate(); // 激活窗体
        });
    }

    private static void RunTask(Action action)
    {
        Task.Run(action).ContinueWith(t =>
        {
            if (t is { IsFaulted: true, Exception: not null })
            {
                Output.WriteOutput($"[ERROR] {t.Exception.InnerException?.Message}");
            }
        });
    }

    private void button1_Click(object sender, EventArgs e)
    {
        string text = textBox1.Text;
        string? res = _client.Send("debug", text).GetString();
        WriteOutput(res ?? "");
    }

    private void buttonOpenDataFolder_Click(object sender, EventArgs e)
    {
        System.Diagnostics.Process.Start("explorer.exe", DataPath());
    }
}